#ifndef VD_FLUSH_FILE_BUFFER
#define VD_FLUSH_FILE_BUFFER

# include "vd.h"

NTSTATUS VD_FlushFileBuffer(IN HANDLE FileHandle){

	NTSTATUS			status;
	IO_STATUS_BLOCK		IoStatus;
	PFILE_OBJECT		FileObject = NULL;
	BOOLEAN				IsCached;

	status = ObReferenceObjectByHandle( 
									FileHandle, 
									FILE_READ_DATA,
                                    NULL, 
									KernelMode,                           
									(PVOID*)&FileObject, 
									NULL 
									);
	
	if (!NT_SUCCESS(status)){
		DbgPrint("Can't get Refference to object. Error : %x \n",status);
		return status;
	}
	
	CcFlushCache(
				FileObject->SectionObjectPointer,
				NULL,
				0,
				&IoStatus
				);
	
	status = IoStatus.Status;
	if (!NT_SUCCESS(status))
	{
		DbgPrint("Can't flush file cache.Error :  %x\n",status);
		ObDereferenceObject(FileObject);
		return status;
	}	

	if (!(MmFlushImageSection(FileObject->SectionObjectPointer,MmFlushForWrite)))
	{
		DbgPrint("Can't flush Image Section.Error :  %x\n",status);
		ObDereferenceObject(FileObject);
		return status;
	}


	status = CcPurgeCacheSection(
								FileObject->SectionObjectPointer,
								NULL,
								0,
								FALSE
								);

	if (!NT_SUCCESS(status))
	{
		DbgPrint("Can't purge file cache.Error :  %x\n",status);
		ObDereferenceObject(FileObject);
		return status;
	}
	
		
	IsCached = CcIsFileCached(FileObject);
	DbgPrint("Is File Cached  %d \n",IsCached);
	DbgPrint("File cache flushed \n");
	ObDereferenceObject(FileObject);
	return status;

}

#endif